*** Settings ***
Resource    ../Common_Head.robot
Library    ../../lib/ExcelLibTest.py
Library    AllureLibrary

*** Variable ***
${G_TENDERID}    0
# #############     INT1
# ${URL}    https://space-int.weu.signintra.com/nges-portal/secured/#!/portal-entry/eschenker
${URL}    https://space-int.weu.signintra.com/
${USERNAME}    AUTOTEST
${USERNAME_FULL}    Automation Tester(AUTOTEST)
${DOWNLOAD_PATH}    ~/Downloads
${HEADLESS}    False
# ${EXECUTE_PATH}    /usr/bin/microsoft-edge-beta
${EXECUTE_PATH}    C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe
# #############     Login Page
${Login_User_Name_Input}    xpath = //input[@name='username']   # login input
${Login_Button}    xpath = //input[@value='Sign In']    #sign in button
${Space_Icon}    css = .app-space-icon-64
${DashBoard_Search}    css = [data-tr='locator.search']
${resolution}    {'width': 1280, 'height': 720}

*** Keywords ***
Login Space
    [Documentation]
    @{Options}     Create List    --start-maximized    --lang=en-US
    ${DOWNLOAD_PATH}     Normalize Path    ${DOWNLOAD_PATH}
    New Browser     browser=chromium    headless=${HEADLESS}    executablePath=${EXECUTE_PATH}    downloadsPath=${DOWNLOAD_PATH}    args=${Options}    channel=Edge
    IF   ${HEADLESS} == False
            ${resolution}    Set Variable    None
    END   
    New Context    hasTouch=True    acceptDownloads=True    viewport=${resolution}
    Sleep    2
    Wait Until Keyword Succeeds    10x    30s    Reload Browser
    Fill Text    ${Login_User_Name_Input}    ${USERNAME}
    Click    text=Sign In
    Wait For Elements State     ${Space_Icon}    enabled     60
    Click    ${Space_Icon}
    Wait For Elements State    ${home_page_table_row}    visible    60
    ${status}    Run Keyword And Return Status    Get Element States    ${navigation_pricing_collaboration}    contains    visible
    IF    "${status}" != "True"
        Click    ${navigation_arrow}
    END
    Wait For Elements State    ${navigation_pricing_collaboration}    visible    

Switch User
    Close Page
    Wait Until Keyword Succeeds    10x    1s    Reload Browser
    Fill Text    ${Login_User_Name_Input}    ${USERNAME}
    Click    text=Sign In
    Wait For Elements State     ${Space_Icon}    enabled     60
    Click    ${Space_Icon}
    Wait For Elements State    ${home_page_table_row}    visible    30
    ${status}    Run Keyword And Return Status    Get Element States    ${navigation_pricing_collaboration}    contains    visible
    IF    "${status}" != "True"
        Click    ${navigation_arrow}
    END
    Wait For Elements State    ${navigation_pricing_collaboration}    visible

Reload Browser
     New Page    ${URL}
    #  ${status}    Run Keyword And Return Status    Wait For Elements State   //a[.='SPACE home page']    enabled    timeout=30s
    #  IF    '${status}'=='True'
    #        Click    text=SPACE home page
    #        Wait For Elements State   xpath = //a[.='Login']    enabled    timeout=20s
    #        Click    xpath = //a[.='Login']
    #  END
    #  ${status}    Run Keyword And Return Status    Wait For Elements State   ${Login_User_Name_Input}    enabled    timeout=5s
    #  IF    '${status}'=='False'
    #        Click    text=eSchenker home page
    #        Wait For Elements State   xpath = //a[.='Login']    enabled    timeout=20s
    #        Click    xpath = //a[.='Login']
    #  END
     ${status}    Run Keyword And Return Status    Wait For Elements State   xpath = //a[.='Login']    enabled    timeout=30s
     IF    '${status}'=='True'
           Click    xpath = //a[.='Login']
     END
     ${status}    Run Keyword And Return Status    Wait For Elements State   ${Login_User_Name_Input}    enabled    timeout=30s
     IF    '${status}'=='False'
           Close Page
     END
     Should Be Equal As Strings    ${status}    True

Wait Until Search Finished    
    [Documentation]    wait until search is finished ---Bella
    Wait Until Keyword Succeeds   600    1    Get Element States    ${search_in_progress}     not contains    visible

Check Value
    [Documentation]    Compare the element value
    [Arguments]    ${Element}    ${expectedValue}    ${property}=value
    Get Attribute    ${Element}    ${property}    equal    ${expectedValue}

Generate Tender ID
    [Documentation]    generate a random tender id   -Bella
    ${randomNum}=    Evaluate    random.randint(00000,99999)    modules=random
    ${TenderId}     Catenate    AUTO    ${randomNum}
    [RETURN]    ${TenderId}

Check Text Value
    [Documentation]    Compare the element text-----Betty
    [Arguments]    ${Element}    ${expectedValue}
    Wait For Elements State    ${Element}    visible    
    Get Text    ${Element}    ==    ${expectedValue}

Get Download File Name
    [Documentation]   get download file name if the file name is random,
    ...    argument filenamepattern is file name prefix   -Bella
    ...    For example, ${fileNanme}    Get Download File Name    AUTO 34959-LCL-Regress_Round    
    [Arguments]    ${fileNamePattern}    ${fileType}=.xlsx
    Wait Until Search Finished
    ${DOWNLOAD_PATH}     Normalize Path    ${DOWNLOAD_PATH}
    Wait Until Keyword Succeeds    20x    500ms    File Should Exist    ${DOWNLOAD_PATH}${/}${fileNamePattern}*${fileType}
    ${FILES}    List Files In Directory   ${DOWNLOAD_PATH}    ${fileNamePattern}*${fileType}
    [Return]    ${DOWNLOAD_PATH}${/}${FILES}[0]

Check Cell Value
    [Documentation]    Check Excel cell value is equal to expected value --Bella
    [Arguments]    ${row}    ${column}    ${expectedValue}    ${sheetName}=None
    ${cellValue}    Read Excel Cell    ${row}   ${column}    ${sheetName}
    Should Be Equal As Strings    ${cellValue}    ${expectedValue}

Click if Enabled
    [Documentation]    Click if it is enabled -Bella
    [Arguments]    ${locator}
    ${ifEnabled}    Run Keyword And Return Status    Get Element States     ${locator}    contains    enabled
    IF    '${ifEnabled}' == 'True'
        Click     ${locator}
    END

Get Excel Column Index
    [Documentation]    get column index by column title  -Bella
    [Arguments]    ${columnTitle}    ${rowIndex}=1
    ${titleList}    Read Excel Row    ${rowIndex}
    ${index}    Get Index From List    ${titleList}    ${columnTitle}
    [Return]    ${index+1}

Remove All Files
    Empty Directory    ${DOWNLOAD_PATH}

InitSpace
    ${DOWNLOAD_PATH}     Normalize Path    ${DOWNLOAD_PATH}
    ${exists}    Run Keyword And Return Status    Directory Should Exist    ${DOWNLOAD_PATH}
    IF    '${exists}'=='False'
          Create Directory    ${DOWNLOAD_PATH}
    END
    Empty Directory    ${DOWNLOAD_PATH}

CloseSpace
    Close Browser
    Set Global Variable    ${USERNAME}    AUTOTEST

Download File
    [Documentation]    Click Download Button, get download file name (contain download path)
    [Arguments]    ${downloadButton}
    ${DOWNLOAD_PATH}     Normalize Path    ${DOWNLOAD_PATH}
    ${dl_promise}    Promise To Wait For Download    ${DOWNLOAD_PATH}${/}aaaa.xlsx
    Wait Until Keyword Succeeds    10x    400ms    Click     ${downloadButton}
    Wait Until Search Finished
    ${file_obj}=     Wait Until Keyword Succeeds    30x    2s     Wait For  ${dl_promise}
    Copy File    ${file_obj}[saveAs]    ${DOWNLOAD_PATH}${/}${file_obj}[suggestedFilename]
    Remove File    ${DOWNLOAD_PATH}${/}aaaa.xlsx
    [Return]     ${DOWNLOAD_PATH}${/}${file_obj}[suggestedFilename]

Navigation Space
    [Documentation]    Navigate on left side   ---Betty
    ...    example: Pricing Collaboration    Push Pricing    Start
    [Arguments]    ${mainMenu}    ${subMenu}=${EMPTY}    ${thirdMenu}=${EMPTY}
    IF    '${subMenu}' == '${EMPTY}'
        Click    xpath = //a[.='${mainMenu}']
    ELSE IF    '${thirdMenu}' == '${EMPTY}'
        ${status}=    Run Keyword And Return Status    Wait For Elements State    //a[.='${subMenu}']    visible    timeout=10s
        IF     ${status} != True
            Click    //a[.='${mainMenu}']
        END
        Click    //a[.='${subMenu}']
    ELSE
        ${status}=    Run Keyword And Return Status    Wait For Elements State    //a[.='${subMenu}']    visible    timeout=10s
        IF     ${status} != True
            Click    //a[.='${mainMenu}']
        END
        Click     //a[.='${subMenu}']
        Click    //a[.='${thirdMenu}']
    END

Compare Excel Value 
    [Documentation]    compare two excel files  ---Nella
    [Arguments]    ${file1}    ${file2}    ${columnMax}    ${rowMax}    ${sheetName}=AIR    ${startRow}=1    ${startColumn}=1
    Close All Excel Documents
    Open Excel Document   ${file1}    file1
    Open Excel Document   ${file2}    file2
    FOR    ${row}    IN RANGE    ${startRow}    ${rowMax}+1    1
        FOR    ${col}    IN RANGE    ${startColumn}    ${columnMax}+1    1
            Switch Current Excel Document    file1
            ${cell1}    Read Excel Cell    ${row}   ${col}    ${sheetName}
            Convert To String    ${cell1}
            Switch Current Excel Document    file2
            ${cell2}    Read Excel Cell    ${row}   ${col}    ${sheetName}
            Convert To String    ${cell2} 
            IF    """${cell1}""" != """${cell2}"""    
            Fail    row${row} column${col} value is different.
            END
        END
    END
    Close All Excel Documents

 Compare Excel Value Only For Data
    [Documentation]    Compare two excel files Only For Data
    [Arguments]    ${file1}    ${file2}    ${columnMax}    ${rowMax}    ${sheetName}=AIR    ${startRow}=1    ${startColumn}=1
    Close All Excel Documents
    Open Excel Document   ${file1}    file1
    Open Excel Document   ${file2}    file2
    FOR    ${row}    IN RANGE    ${startRow}    ${rowMax}+1    1
        FOR    ${col}    IN RANGE    ${startColumn}    ${columnMax}+1    1
            Switch Current Excel Document    file1
            ${cell1}    Read Excel Cell    ${row}   ${col}    ${sheetName}
            Switch Current Excel Document    file2
            ${cell2}    Read Excel Cell    ${row}   ${col}    ${sheetName}
            ${isNumber1}    Run Keyword And Return Status    Convert To Number    ${cell1}
            ${isNumber2}    Run Keyword And Return Status    Convert To Number    ${cell2}
            IF    '${isNumber1}' == 'True'
                ${result}    Evaluate    float(${cell1}) != float(${cell2})
                    IF    ${result}
                        Fail    row${row} column${col} value is different.
                    END
            END
        END
    END
    Close All Excel Documents   

Check All Check Box for Page
    [Arguments]    ${SpecialPageElement}
    # for legend: ${SpecialPageElement}=//legend[contains(.,"${legend}")]/following-sibling::div
    # for sectionClass: ${SpecialPageElement}=//section[@class="${sectionClass}"]
    Wait Until Search Finished
    Wait Until Search Finished
    ${Tabindex}    Set Variable        1
    ${checkboxindex}    Set Variable        1
    ${uncheckedbox}    Set Variable    ${SpecialPageElement}/div//input[@type="checkbox"][contains(@class, 'ng-empty')]
    ${TabName}    Set Variable    ${SpecialPageElement}/div//li/a[@class='ng-binding']
    ${count}    Get Element Count    ${uncheckedbox}
    # ${count}    Set Variable    10
    ${TabCount}    Get Element Count    ${TabName}
    ${end}    Evaluate    int(${count}+1)
    Click    (${TabName})[1]
    # ${TabEnd}    Evaluate    int(${TabCount}+1)
    FOR    ${index}    IN RANGE    1    ${end}    1
        Log    ${index}
        ${originalcount}    Get Element Count    ${uncheckedbox}
        ${status}    Run Keyword And Return Status    Get Element States    (${uncheckedbox})[${checkboxindex}]    contains    visible
        IF    '${status}' == 'True'
            Click    (${uncheckedbox})[${checkboxindex}]
            ${currentcount}    Get Element Count    ${uncheckedbox}
            IF    ${currentcount} == ${originalcount}
                ${checkboxindex}    Evaluate    int(${checkboxindex}+1)
            END
        ELSE
            ${Tabindex}    Evaluate    int(${Tabindex}+1)
            IF    ${TabCount} < ${Tabindex}
                Exit For Loop
            END
            Log    ${Tabindex}
            Click    (${TabName})[${Tabindex}]
            ${originalcount}    Get Element Count    ${uncheckedbox}
            ${visibleStatus}    Run Keyword And Return Status    Get Element States    (${uncheckedbox})[${checkboxindex}]    contains    visible
            IF    '${visibleStatus}' == 'True'
                    Click    (${uncheckedbox})[${checkboxindex}]
                    ${currentcount}    Get Element Count    ${uncheckedbox}
                    IF    ${currentcount} == ${originalcount}
                         ${checkboxindex}    Evaluate    int(${checkboxindex}+1)
                    END
            END
        END
        ${currentcount}    Get Element Count    ${uncheckedbox}
    END


Space Teardown
    Run Keyword If Test Failed    Take Screenshot In Allure
    Reload
    Run Keyword And Ignore Error    Delete Project    ${G_TENDERID}
    Run Keyword And Ignore Error    Delete Tender    ${G_TENDERID}
    CloseSpace

Take Screenshot In Allure
    ${path}=    Take Screenshot    ErrorJpg/error
    Attach File    ${path}